#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos;
Stoc stoc;

void transf_acc(void)
{
	char path[PATH_MAX];
	char path_transf[PATH_MAX];
	Account temp;
	Account temp_transf;
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);
	pf("acc path:%s\n",path);
	int fd = open(path,O_RDONLY);
	if(0 > fd)
	{
		perror("open acc");
		strcpy(stoc.str,"未找到该用户，请确认账号");
	}
	read(fd,&temp,sizeof(Account));
	close(fd);
	
	sprintf(path_transf,"%s/%u",ACC_PATH,ctos.acc.transf_id);
	pf("acc path:%s\n",path);
	int fd_transf = open(path,O_RDONLY);
	if(0 > fd_transf)
	{
		perror("open acc");
		strcpy(stoc.str,"未找到该用户，请确认账号");
	}
	read(fd_transf,&temp_transf,sizeof(Account));
	close(fd_transf);
	
	if(ctos.acc.money <= 0)
	{
		strcpy(stoc.str,"不能输入0及0以下的数字");
	}
	else if(ctos.acc.money <= temp.money)
	{
		temp_transf.money += ctos.acc.money;
		temp.money -= ctos.acc.money;
		strcpy(stoc.str,"转账成功");
	}
	else
	{
		strcpy(stoc.str,"余额不足");
	}
	
	int fd1 = open(path,O_WRONLY);
	write(fd1,&temp,sizeof(Account));
	close(fd1);
	
	int fd1_transf = open(path_transf,O_WRONLY);
	write(fd1_transf,&temp_transf,sizeof(Account));
	close(fd1_transf);
	
	stoc_send(&stoc);
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_TRANSF);
		stoc.type = ctos.pid;
		transf_acc();
	}
}
